package com.lksy.web.controller.system;

import javax.inject.Inject;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.lksy.web.controller.BaseController;
import com.lksy.web.service.system.AdminService;

/**
 * 整个系统登录界面处理器
 * @author jzx
 * @date 2016-08-01 下午 13:34 星期一 建军节
 */
@Controller
@RequestMapping("system")
public class SystemLoginController extends BaseController {

	@Inject
	private AdminService adminService;
	
	/**
	 * 登录执行方法
	 */
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String login() {
		return "/system/login";
	}
	
	/**
	 * 执行登出
	 */
	@RequestMapping(value = "logout")
	public String logout() {
		removeSessionAttr("username");
		return "/system/login";
	}
	
	/**
	 * 首页执行方法
	 */
	@RequestMapping(value = "/main")
	public String main() {
		return "/system/main";
	}
	
	/**
	 * 跳转到修改密码页面
	 */
	@RequestMapping(value = "/toUpdatePwd")
	public String toUpdatePwd(Model model) {
		model.addAttribute("mainPage", "/system/updatePwd");
		return "/system/main";
	}
	
	/**
	 * 跳转到修改密码页面
	 */
	@RequestMapping(value = "/updatePwd")
	public String updatePwd(Model model) {
		return "/system/updatepwd";
	}
	
	
	
	/**
	 * 登陆方法执行逻辑代码
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/login" , method = RequestMethod.POST)
	public String login(@RequestParam("username") String name,
						@RequestParam("password") String paswd,
						@RequestParam("imageValue") String image,Model model) {

		// 获取自动生成的验证码
		String code = (String) getSessionAttr("code");

		if(StringUtils.isEmpty(name) || StringUtils.isEmpty(paswd)) {
			model.addAttribute("error", "用户名或者密码不能为空！！！！");
		} 
		else if(StringUtils.isEmpty(image)) {
			model.addAttribute("error", "验证码或者图片不能为空！！！");
		} 
		else if (!image.equalsIgnoreCase(code)) {
			model.addAttribute("error", "验证码输入错误，please try again ！！！");
		} else {
			if(adminService.login(name, paswd)) {
				removeSessionAttr("code");
				setSessionAttr("username", name);
				return "/system/main";
			} else {
				model.addAttribute("error", "用户名或者密码不存在！！！！");
			}
		}
		return "/system/login";
	}
}
